import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:provider/provider.dart';
import 'package:trade/common/service/router_service/router_table.dart';
import 'package:trade/common/service/td_service.dart';
import 'package:trade/data/model/user_model.dart';
import 'dart:convert';
import 'package:crypto/crypto.dart';
import 'package:trade/pages/login_page/login_model.dart';
import 'package:trade/theme/app_colors.dart';

class LoginPage extends StatefulWidget {
  @override
  _LoginPageState createState() => _LoginPageState();
}

class _LoginPageState extends State<LoginPage> {
  LoginModel _model = LoginModel();

  TextEditingController _accountController = TextEditingController(text: "");
  TextEditingController _passwordController = TextEditingController(text: "");
  FocusNode _accountFocus = FocusNode();
  FocusNode _passwordFocus = FocusNode();
  bool _acFo = false;
  bool _pwFo = false;

  @override
  void initState() {
    _accountFocus.addListener(_accountFocusListener);
    _passwordFocus.addListener(_passwordFocusListener);
    super.initState();
  }

  void _accountFocusListener() {
    setState(() {
      _acFo = _accountFocus.hasFocus;
    });
  }

  void _passwordFocusListener() {
    setState(() {
      _pwFo = _passwordFocus.hasFocus;
    });
  }

  @override
  void dispose() {
    _accountController.dispose();
    _passwordController.dispose();
    _accountFocus.dispose();
    _passwordFocus.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        backgroundColor: appColors.backgroundColor,
        appBar: AppBar(
          toolbarHeight: kToolbarHeight,
        ),
        resizeToAvoidBottomInset: false,
        body: SafeArea(
          child: Container(
            color: appColors.backgroundColor,
            padding: EdgeInsets.symmetric(horizontal: 24).copyWith(top: 120),
            child: Column(
              mainAxisAlignment: MainAxisAlignment.start,
              children: [
                _buildAccountField(),
                SizedBox(height: 15),
                _buildPasswordField(),
                SizedBox(height: 15),
                _buildLoginButton()
              ],
            ),
          ),
        ));
  }

  Widget _buildAccountField() {
    return SizedBox(
      height: 50,
      child: TextField(
        controller: _accountController,
        focusNode: _accountFocus,
        autofocus: true,
        style: TextStyle(
          fontSize: 15,
        ),
        inputFormatters: [FilteringTextInputFormatter.digitsOnly],
        keyboardType: TextInputType.number,
        maxLength: 11,
        buildCounter: (context,
                {required int currentLength,
                required bool isFocused,
                maxLength}) =>
            Text(''),
        decoration: InputDecoration(
          contentPadding: EdgeInsets.only(left: 10, bottom: 10, top: 10),
          hintText: "请输入手机号码",
          hintStyle: TextStyle(fontSize: 15, color: Colors.grey[500]),
          suffixIcon: _acFo
              ? InkWell(
                  onTap: () {
                    _accountController.text = "";
                    _accountFocus.unfocus();
                  },
                  child: Container(
                    width: 20,
                    height: 20,
                    child: Icon(
                      Icons.cancel,
                      size: 18,
                    ),
                  ),
                )
              : SizedBox(),
        ),
      ),
    );
  }

  Widget _buildPasswordField() {
    return SizedBox(
      height: 50,
      child: TextField(
        controller: _passwordController,
        focusNode: _passwordFocus,
        autofocus: true,
        obscureText: true,
        style: TextStyle(
          fontSize: 15,
        ),
        keyboardType: TextInputType.visiblePassword,
        maxLength: 8,
        buildCounter: (context,
                {required int currentLength,
                required bool isFocused,
                maxLength}) =>
            Text(''),
        decoration: InputDecoration(
          contentPadding: EdgeInsets.only(left: 10, bottom: 10, top: 10),
          hintText: "请输入密码",
          hintStyle: TextStyle(fontSize: 15, color: Colors.grey[500]),
          suffixIcon: _pwFo
              ? InkWell(
                  onTap: () {
                    _passwordController.text = "";
                    _passwordFocus.unfocus();
                  },
                  child: Container(
                    width: 20,
                    height: 20,
                    child: Icon(
                      Icons.cancel,
                      size: 18,
                    ),
                  ),
                )
              : SizedBox(),
        ),
      ),
    );
  }

  Widget _buildLoginButton() {
    return Consumer(
      builder: (context, UserModel userModel, _) {
        return Container(
          width: double.infinity,
          height: 40,
          decoration: BoxDecoration(
            borderRadius: BorderRadius.circular(6),
          ),
          child: TextButton(
            onPressed: () async {
              _accountFocus.unfocus();
              _passwordFocus.unfocus();
              var password = "[p" + _passwordController.text + "d]";
              password = md5.convert(utf8.encode(password)).toString().toUpperCase();
              var isLogin = await _model.login(
                  phone: _accountController.text,
                  password: password,
                  userModel: userModel);
              if (isLogin) {
                service.router.pushReplacementNamed(RouteName.tradingPage);
              }
            },
            child: Text(
              "登录",
              style: TextStyle(
                  fontSize: 15,
                  fontWeight: FontWeight.bold,
                  color: Colors.white),
            ),
            style: ButtonStyle(
              backgroundColor: MaterialStateProperty.all(appColors.text1),
            ),
          ),
        );
      },
    );
  }
}
